import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import React from 'react';
import PropTypes from 'prop-types';
import { checkPermission } from "../../services/api";
import { getResponse } from "../../utils/utils";
import { FAILURE, SUCCESS } from "./Status";
var DELAY = 500;

var PermissionProvider = /*#__PURE__*/function (_React$Component) {
  _inherits(PermissionProvider, _React$Component);

  var _super = _createSuper(PermissionProvider);

  function PermissionProvider() {
    var _this;

    _classCallCheck(this, PermissionProvider);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.delayId = 0;
    _this.allPermissionCodeList = new Set();
    _this.permissions = new Map();
    _this.controllerTypes = new Map();
    _this.queue = new Set();
    _this.handlers = new Set();
    return _this;
  }

  _createClass(PermissionProvider, [{
    key: "getChildContext",
    value: function getChildContext() {
      return {
        permission: this
      };
    } // 定时器对象

  }, {
    key: "fetchPermission",
    value:
    /**
     * 请求接口验证权限集
     */
    function fetchPermission() {
      var _this2 = this;

      var handlers = Array.from(this.handlers);
      checkPermission(Array.from(this.queue)).then(function (data) {
        if (getResponse(data)) {
          data.forEach(function (_ref) {
            var code = _ref.code,
                approve = _ref.approve,
                controllerType = _ref.controllerType;

            // 存储权限对象
            if (code) {
              _this2.permissions.set(code, approve ? SUCCESS : FAILURE);

              _this2.controllerTypes.set(code, controllerType);
            }
          }); // 处理权限

          handlers.forEach(function (_ref2) {
            var _ref3 = _slicedToArray(_ref2, 2),
                props = _ref3[0],
                handler = _ref3[1];

            return _this2.check(props, handler, true);
          });
        }
      });
    }
    /**
     * 开始验证权限，处理延迟
     */

  }, {
    key: "start",
    value: function start() {
      var _this3 = this;

      if (this.delayId) {
        clearTimeout(this.delayId);
      }

      this.delayId = setTimeout(function () {
        _this3.fetchPermission();

        _this3.queue.clear();

        _this3.handlers.clear();
      }, DELAY);
    }
    /**
     * 处理权限
     * @param {object} props - 参数
     * @param {function} handler - 回调函数
     * @param {boolean} flag - 标记
     */

  }, {
    key: "check",
    value: function check(props, handler, flag) {
      var _this4 = this;

      // 设置了 code 属性才去验证权限，没设置权限将直接返回成功状态
      if (!props.permissionList || props.permissionList.length === 0) {
        handler(SUCCESS);
      } else {
        var _props$permissionList = props.permissionList,
            permissionList = _props$permissionList === void 0 ? [] : _props$permissionList;
        var codeList = permissionList.map(function (item) {
          return item.code.replace(/^\//g, '').replace(/\//g, '.').replace(/:/g, '-');
        });
        var queue = new Set(); // 遍历找到对应的需要验证权限的对象

        var isCheckThrough = codeList.every(function (item) {
          if (item) {
            _this4.allPermissionCodeList.add(item);

            var key = item; // 获取对应待验证对象的权限状态

            var status = _this4.permissions.get(key); // 验证成功后执行回调函数，结束验证


            if (status === SUCCESS) {
              var ctlType = _this4.controllerTypes.get(item);

              handler(status, ctlType);
              return false;
            } else if (status !== FAILURE) {
              // 没有被验证的放入队列中等待下次验证
              _this4.queue.add(key);

              queue.add(key);
            }
          }

          return true;
        });

        if (isCheckThrough) {
          // 再一次验证剩余的权限
          if (queue.size > 0 && !flag) {
            this.handlers.add([props, handler]);
            this.start();
          } else {
            // 鉴权失败后执行回调函数
            codeList.some(function () {
              handler(FAILURE);
              return true;
            });
          }
        }
      }
    }
  }, {
    key: "render",
    value: function render() {
      return this.props.children;
    }
  }]);

  return PermissionProvider;
}(React.Component);

PermissionProvider.childContextTypes = {
  permission: PropTypes.object
};
export { PermissionProvider as default };